package epis.unsa;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.log.Log;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class AdaServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        if(user == null)
        	resp.sendRedirect("login.jsp");
        else {
	        String scui = req.getParameter("cui");
	        String firstname = req.getParameter("firstname");
	        String lastname = req.getParameter("lastname");
	        String email = user.toString();
	        String handle = req.getParameter("handle");
	        
	        if(scui == "" || firstname == "" || lastname == "" || email == "" || handle == "")
	        	resp.sendRedirect("error.jsp");
	        else {
		        Long cui = new Long(scui);
		        
		        //System.out.println(email);
		        
		        if(userExist(email) != null)
		        	resp.sendRedirect("welcome.jsp");
		        else {
			        if(!checkHandle(handle))
			        	resp.sendRedirect("errorHandle.jsp");
			        else{
				        if(isNew(cui,email,handle)){
				        	Date date = new Date();
				        	Alumno student = new Alumno(cui, firstname, lastname, email, handle, date);
				        	PersistenceManager pm = PMF.get().getPersistenceManager();
				            try {
				                pm.makePersistent(student);
				            } finally {
				                pm.close();
				            }
				            resp.sendRedirect("welcome.jsp");
				        }else
				        	resp.sendRedirect("error.jsp");
			        }
		        }
	        }
        }
	}
	
	private Alumno userExist(String user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
        String query = "select from " + Alumno.class.getName() +
		   			   " where handle == '" + user + "'";
        List<Alumno> students = (List<Alumno>) pm.newQuery(query).execute();
        if(students.isEmpty())
        	return null;
		return students.get(0);
	}

	/**
	 * Check if the data is unique.
	 * @param cui
	 * @param email
	 * @param handle
	 * @return
	 */
	public boolean isNew(long cui, String email, String handle){
		return uniqueCui(cui) && uniqueEmail(email) && uniqueHandle(handle);
	}
	
	public boolean uniqueCui(long cui){
		PersistenceManager pm = PMF.get().getPersistenceManager();
        String query = "select from " + Alumno.class.getName() +
        			   " where cui == " + cui;
        List<Alumno> students = (List<Alumno>) pm.newQuery(query).execute();
        if(students.isEmpty())
        	return true;
		return false;
	}
	
	public boolean uniqueHandle(String handle){
		PersistenceManager pm = PMF.get().getPersistenceManager();
        String query = "select from " + Alumno.class.getName() +
        			   " where handle == '" + handle + "'";
        List<Alumno> students = (List<Alumno>) pm.newQuery(query).execute();
        if(students.isEmpty())
        	return true;
		return false;
	}
	
	public boolean uniqueEmail(String email){
		PersistenceManager pm = PMF.get().getPersistenceManager();
        String query = "select from " + Alumno.class.getName() +
        			   " where email == '" + email + "'";
        List<Alumno> students = (List<Alumno>) pm.newQuery(query).execute();
        if(students.isEmpty())
        	return true;
		return false;
	}
	/**
	 * Check if handle exist in topcoder
	 * @param handle
	 * @return
	 */
	public boolean checkHandle(String handle){
		try {
			URL url = new URL("http://www.topcoder.com/tc?module=SimpleSearch&ha="+handle);
			BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;

            while ((line = reader.readLine()) != null) {
            	if(line.indexOf("Your search returned 0 matches.") >= 0)
            		return false;
            }
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
}
